﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Collections.Generic;
using Microsoft.SharePoint;
using System.Data;

namespace JM.JCY.SharePointComponent.Survey.SurveyHome
{
    public partial class SurveyHomeUserControl : UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                DataTable dt = new DataTable();
                dt.Columns.Add("Title");
                dt.Columns.Add("Link");
                dt.Columns.Add("CreatedTime");
                SPWeb web = SPContext.Current.Web;
                foreach (SPList list in web.Lists)
                {
                    if (list.BaseType == SPBaseType.Survey)
                    {
                        DataRow newRow = dt.NewRow();
                        newRow["Title"] = list.Title.ToString();
                        newRow["Link"] = list.DefaultViewUrl.ToString();
                        newRow["CreatedTime"] = list.Created;
                        dt.Rows.Add(newRow);
                    }

                }

                //Get the TOP 5 Survey ORDER BY Created Time
                DataView dv = dt.DefaultView;
                dv.Sort = "CreatedTime Desc";
                dt = dv.ToTable();
                if(dt.Rows.Count > 5)
                    dt = SelectTopDataRow(dt, 5);
               
                this.gvBC.DataSource = dt;
                this.gvBC.DataBind();


             
            }

        }


     

        protected void gvBC_DataBound(object sender, GridViewRowEventArgs e)
        {
            var drv = (DataRowView)e.Row.DataItem;
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                Literal Link = (Literal)e.Row.Cells[0].FindControl("ltRedirect");
                Link.Text = "<img src='/_layouts/images/itsurvey.png'>&nbsp;&nbsp;<a href='" + drv["Link"].ToString() + "'>" + drv["Title"].ToString() + "</a>";
                
             }

        }

        public DataTable SelectTopDataRow(DataTable dt, int count)
        {
            DataTable sDT = dt.Clone();
            for (int i = 0; i < count; i++)
            {
                sDT.ImportRow(dt.Rows[i]);
            }

            return sDT;
        }

        protected void lbViewAllAnn_Click(object sender, EventArgs e)
        {
            Response.Redirect(SPContext.Current.Site.ServerRelativeUrl + "SurveyPages/ViewAllSurvey.aspx");
        }
    }
}
